package entry;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder.Builder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * SpringBoot启动入口 
 * @author libra
 */
//标注该类为SpringBoot的主配置类
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})// 排除前端门户的数据库自动装配
/*
 * @EnableEurekaClient 与 @EnableDiscoveryClient
 * 在功能上是一致的：写在启动类的上，开启服务注册发现功能。
 * @EnableEurekaClient只适用于Eureka作为注册中心，@EnableDiscoveryClient 可以是其他注册中心。
 */
// 开启EurekaClient的注解，连接EurekaServer
//@EnableEurekaClient
@EnableDiscoveryClient
public class MainStart_Gateway_20900 {
	public static void main(String[] args) {
		ConfigurableApplicationContext cac = SpringApplication.run(MainStart_Gateway_20900.class, args);
	}
	
	/**
	 * Gateway除了在yml中配置路由routes，还可以通过编码的形式配置路由routes
	 * https://www.bilibili.com/movie
	 */
	@Bean
	public RouteLocator routes( RouteLocatorBuilder builder ) {
		Builder routes = builder.routes();
		// 设置路由的唯一ID、path断言匹配、对应的访问路径
		// 访问 http://127.0.0.1:20900/movie -> 跳转bilibili
		routes = routes.route("code_gateway_id",  
				(r) -> { return r.path("/movie").uri("https://www.bilibili.com"); } );
		return routes.build();
	}
	
	/**
	 * 基于代码配置的方式，解决Cros跨域请求问题
	 * @return
	 */
//	@Bean
	public CorsWebFilter corsFilter() {
		CorsConfiguration config = new CorsConfiguration();
		// 允许的请求方式
		config.addAllowedMethod("*");
		// 允许的请求头
		config.addAllowedHeader("*");
		// 允许的请求来源
		config.addAllowedOrigin("*");
		// 允许访问的资源
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
		source.registerCorsConfiguration("/**", config);
		
		return new CorsWebFilter(source);
	}
}
